import React, {useEffect, useLayoutEffect, useState} from 'react';
import {Dimensions, SafeAreaView, ScrollView, StyleSheet, View} from 'react-native';
import {defaultNavigationConfigure} from "../../base/navconfig";
import {LoadingView} from "react-native-gzdsx-elements";
import ApiService from "../../utils/ApiService";
import RenderHTML from "react-native-render-html";
import {useNavigation, useRoute} from "@react-navigation/native";
import StatusBarCtl from "../../utils/StatusBarCtl";

export default function () {
    const route = useRoute();
    const navigation = useNavigation();
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState({});

    useLayoutEffect(() => {
        fetchData();
        navigation.setOptions({
            ...defaultNavigationConfigure(navigation),
            title: '',
        });

        return navigation.addListener('focus', () => {
            StatusBarCtl.setToDarkStyle();
        });
    }, []);

    const fetchData = () => {
        ApiService.get('/pages/' + route.params.id).then(response => {
            setPage(response.result);
            navigation.setOptions({title: response.result.title});
        }).catch(reason => {
            console.log(reason.message);
        }).finally(() => {
            setLoading(false);
        })
    }

    if (loading) {
        return <LoadingView/>;
    }

    return (
        <SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
            <ScrollView style={{flex: 1}}>
                <View style={styles.body}>
                    <RenderHTML
                        source={{html: page.content}}
                        contentWidth={Dimensions.get('window').width - 30}
                        renderersProps={{
                            img: {
                                enableExperimentalPercentWidth: true
                            }
                        }}
                        baseStyle={{
                            fontSize: 18,
                            fontWeight: '350',
                            color: '#333',
                            lineHeight: 28
                        }}
                        emSize={0}
                        enableExperimentalMarginCollapsing={true}
                        ignoredDomTags={['a', 'div']}
                    />
                </View>
            </ScrollView>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    header: {
        paddingVertical: 10,
        paddingHorizontal: 15
    },
    body: {
        paddingHorizontal: 15,
        textAlign: 'justify'
    }
});
